ajax方法调用Web API,谁消耗了GRPC服务(如何从DB中获取列表?):错误415和400

发布于 2025-02-01 14:33:35 字数 3669 浏览 4 评论 0原文

我在Web控制台中遇到问题,首先给我错误的415没有contentType:'application/json; charset = utf-8',在ajax方法中,它给了我错误400。

如果错误在后端代码中,我也尝试进行调试,调试器应该运行...)

我的目标是返回用户及其电子邮件的列表,类似这样

//试图在我的服务中执行此操作
iEnumerable()

// c#
类 弹奏者:
(字符串)用户名:user1
(字符串)电子邮件:

” GRPC,所以我将拥有一个Web API控制器,称为GRPC方法

,因为GRPC中没有IEnumerable,因此我的原始和方法看起来像这样:

proto:

syntax = "proto3";

option csharp_namespace = "GrpcService1.Protos";

package UserAuth;

service UserAuth {
rpc GetAllUsers(MessageRequest) returns(ListUsersResponse);
}

message ListUserResponse{
     string username = 1;
     string email = 2;
}

message ListUsersResponse{
  repeated ListUserResponse lstUsers = 1;
}

message MessageRequest{
string message = 1;
}

grpc方法服务c#

public override Task<ListUsersResponse> GetAllUsers(MessageRequest request, ServerCallContext context)
        {
            //This gives me an IEnumerable<ShowUsers> (this is
            correct)
            var a = _userBll.getAllUsers();

           //Here in this lines maybe be the problem but I don't
           //know where (maybe be because of json type or something into a list)
           //here im trying to put separate list of users and emails
            var names = a.Select(x => x.Username);
            var emails = a.Select(y => y.Email);

            //here im trying to put the lists into a Response
            var all = new ListUserResponse
            {
                Username = names.ToString(),
                Email = emails.ToString()
            };

            //the above will give the same but the
            ListUsersResponse is a repeated attribute
            var response = new ListUsersResponse
            {
                LstUsers = { all }
            };

            //all ok
            request.Message = "Sucess";

            return Task.FromResult(response);
        }

下面的代码是正确的(i用邮政方法测试我在没有GRPC的情况下测试的控制器和Ajax我测试了),但是您将对我在做什么(是控制器和AJAX方法)

控制器[httpget]:

[HttpGet("getAllUserInfo_2"), Authorize]
        public async Task<ActionResult<ListUsersResponse>> GetAll_2([FromBody] MessageRequest message)
        {
            _logger.Log(LogLevel.Information, "Request Received for AuthController::Register");

            var results = await _userClient.GetAllUsersAsync(message);

            _logger.Log(LogLevel.Information, "Sending Response from AuthController::Register");

            return Ok(results);
        }

ajax方法:

$(function b() {
    debugger;
    var $users_A = $('#users_A');
    $.ajax({
            contentType: 'application/json; charset=UTF-8', //if I comment this gives me 415
            url: uri_3_2,
            type: 'GET',
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
            },
            success: function(date) {
                $.each(data, function (i, rice) {
                    $users_A.append('<li>Name: ' + arroz.username + ' Email: ' + arroz.email + ' </li>');
                });
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('XHR:' + xhr + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);   //this should give me more info about the error but don't works... But it 
                //works fine the implementation code
                $users_A.append('<h4>ERRRROORRRR</h4>');
            }
        });
    });


欢迎任何帮助

I have problems in my web console, first it gives me error 415 without contentType: 'application/json; charset=UTF-8', in ajax method and with it gives me error 400.

I also try doing debug if the error is in backend code but it never happens and it jumps off (this don't make any sense, the debugger should run...)

My goal is to return a list of users and their email, something like this

//trying to do this in my service
IEnumerable()

//class c#
ShowUsers:
(string)Username: User1
(string)Email:[email protected]

But I'm doing this in gRPC, so I'll have a web API controller calling the gRPC method

As there is no IEnumerable in gRPC, so my proto and method look like this:

Proto:

syntax = "proto3";

option csharp_namespace = "GrpcService1.Protos";

package UserAuth;

service UserAuth {
rpc GetAllUsers(MessageRequest) returns(ListUsersResponse);
}

message ListUserResponse{
     string username = 1;
     string email = 2;
}

message ListUsersResponse{
  repeated ListUserResponse lstUsers = 1;
}

message MessageRequest{
string message = 1;
}

gRPC method service c#

public override Task<ListUsersResponse> GetAllUsers(MessageRequest request, ServerCallContext context)
        {
            //This gives me an IEnumerable<ShowUsers> (this is
            correct)
            var a = _userBll.getAllUsers();

           //Here in this lines maybe be the problem but I don't
           //know where (maybe be because of json type or something into a list)
           //here im trying to put separate list of users and emails
            var names = a.Select(x => x.Username);
            var emails = a.Select(y => y.Email);

            //here im trying to put the lists into a Response
            var all = new ListUserResponse
            {
                Username = names.ToString(),
                Email = emails.ToString()
            };

            //the above will give the same but the
            ListUsersResponse is a repeated attribute
            var response = new ListUsersResponse
            {
                LstUsers = { all }
            };

            //all ok
            request.Message = "Sucess";

            return Task.FromResult(response);
        }

The code below is correct (I test with a POST method the controller and the ajax I test without the gRPC and works fine) but you will have the idea of ​​what I'm doing (its the controller and the ajax method)

Controller [HTTPGET]:

[HttpGet("getAllUserInfo_2"), Authorize]
        public async Task<ActionResult<ListUsersResponse>> GetAll_2([FromBody] MessageRequest message)
        {
            _logger.Log(LogLevel.Information, "Request Received for AuthController::Register");

            var results = await _userClient.GetAllUsersAsync(message);

            _logger.Log(LogLevel.Information, "Sending Response from AuthController::Register");

            return Ok(results);
        }

Ajax Method:

$(function b() {
    debugger;
    var $users_A = $('#users_A');
    $.ajax({
            contentType: 'application/json; charset=UTF-8', //if I comment this gives me 415
            url: uri_3_2,
            type: 'GET',
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
            },
            success: function(date) {
                $.each(data, function (i, rice) {
                    $users_A.append('<li>Name: ' + arroz.username + ' Email: ' + arroz.email + ' </li>');
                });
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('XHR:' + xhr + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);   //this should give me more info about the error but don't works... But it 
                //works fine the implementation code
                $users_A.append('<h4>ERRRROORRRR</h4>');
            }
        });
    });


Any help is welcome

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷离° 2025-02-08 14:33:35

双向流RPC将是一个更好的选择
大大提高您的表现,并可能解决您的问题。

您需要更改原始原型如下:

syntax = "proto3";
option csharp_namespace = "GrpcService1.Protos";
package UserAuth;

service UserAuth {
rpc GetAllUsers(MessageRequest) returns(stream UserResponse);
}

message UserResponse{
     string username = 1;
     string email = 2;
}

message MessageRequest{
     string message = 1;
}

GRPC方法服务C#

public override async Task GetAllUsers(MessageRequest request, IServerStreamWriter<UserResponse> responseStream, ServerCallContext context)
        {
            var users = _userBll.getAllUsers();
            foreach (user in users)
            {
                await responseStream.WriteAsync(new UserResponse
                {
                    Username = user.Username.ToString(),
                    Email = user.Email.ToString()
                });
            }
        }

在客户端中:

    public async Task<List<UserResponse> GetAllUsers()
    {
        var userResponseList = new List<UserResponse>();
        using var call = client.GetAllUsers(new MessageRequest());
        while (await call.ResponseStream.MoveNext())
        {
            var userResponse = new UserResponse
                {
                    Username = call.ResponseStream.Current.Username,
                    Email = call.ResponseStream.Current.Email
                });
            userResponseList.Add(userResponse);
        }
        return userResponseList;
    }

客户端对象来自从GRPC服务URL创建的频道(我假设您知道)。
现在,您可以将其作为服务,并通过控制器的依赖注入来调用它。
我没有测试它,所以它可能会有一些编译错误,但是方法是正确的。

A bi-directional streaming RPC would be a better option as it will
improve your performance significantly and may solve your problem.

you need to change your proto as the following:

syntax = "proto3";
option csharp_namespace = "GrpcService1.Protos";
package UserAuth;

service UserAuth {
rpc GetAllUsers(MessageRequest) returns(stream UserResponse);
}

message UserResponse{
     string username = 1;
     string email = 2;
}

message MessageRequest{
     string message = 1;
}

gRPC method service c#

public override async Task GetAllUsers(MessageRequest request, IServerStreamWriter<UserResponse> responseStream, ServerCallContext context)
        {
            var users = _userBll.getAllUsers();
            foreach (user in users)
            {
                await responseStream.WriteAsync(new UserResponse
                {
                    Username = user.Username.ToString(),
                    Email = user.Email.ToString()
                });
            }
        }

in client:

    public async Task<List<UserResponse> GetAllUsers()
    {
        var userResponseList = new List<UserResponse>();
        using var call = client.GetAllUsers(new MessageRequest());
        while (await call.ResponseStream.MoveNext())
        {
            var userResponse = new UserResponse
                {
                    Username = call.ResponseStream.Current.Username,
                    Email = call.ResponseStream.Current.Email
                });
            userResponseList.Add(userResponse);
        }
        return userResponseList;
    }

the client object has come from the channel which is created from the gRPC service URL (I assume you know it).
Now you can make this a service and call it by dependency injection from your controller.
I didn't test it so it may have some compile errors but the approach is correct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文