【问题标题】:Ajax Get Request to RestApiAjax 获取休息 API 的请求
【发布时间】:2021-05-07 03:38:01
【问题描述】:

我确定这个问题之前已经发布过很多次,并且我已经查看了所有相关主题。但是还是不行。

我们有 JavaScript 部分:

$.ajax({
    type: "GET",
    url: "https://localhost:44346/api/persons/",
    //dataType: "JSON",
    success: function (response) {
        callback("a");
    },
    error: function (response) {
        callback("b");
    }
}
);

还有 C# 部分:

[Route("persons")]
[HttpGet]
public ActionResult GetPersons()
{
    return new JsonResult(new { Success = true, Result = "abc" }, 
    System.Web.Mvc.JsonRequestBehavior.AllowGet);
}

问题是 Jquery 总是有 result = "b" 的错误。 Api 中的断点被命中。我试过有无dataType: "JSON"。将参数发送到 Api 也可以,但返回结果不起作用。所有项目都是 .Net 5.0。

【问题讨论】:

  • 获取响应的详细信息会很有帮助。尤其是状态代码和任何错误消息。
  • 请也发布控制器标题
  • response.statusCode.toString() 给出: f u n c t i o n ( e ) { v a r t ;我 f ( e ) 我 f ( h ) T 。 a l w a y s ( e [ T . s t a t u s ] ) ; e l s e f o r ( t i n e ) w [ t ] = [ w [ t ] , e [ t ] ] ; r e t u r n t h i s }
  • 控制器头:´[ApiController] [Route("api")] public class PersonController : ControllerBase {´

标签: javascript c# jquery model-view-controller


【解决方案1】:

替换

 url: "https://localhost:44346/api/persons/",

  url: "https://localhost:44346/api/persons",

并从您的操作中删除 [HttpGet]。

[Route("~/api/persons")]
public ActionResult GetPersons()
{
    return new JsonResult(new { Success = true, Result = "abc" });
}

但如果 API CORS 配置不正确,您仍然会收到错误响应。 API(不是客户端)启动应该是这样的:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));


            services.AddControllers()
            .AddNewtonsoftJson(options =>
            options.SerializerSettings.ContractResolver =
            new CamelCasePropertyNamesContractResolver());
        }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            app.UseRouting();
            app.UseCors("AllowAnyOrigins");

            //app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

【讨论】:

  • 更改 Url 和/或 Route 后,断点不再在 Api 中命中。也删除 [HttpGet] 没有任何区别。
  • @ProgrammingParadise 对不起,我忘了你在调用 API。我做了一些改变。
  • 我几乎不敢相信。但它现在可以在 6 小时点击 300 次后工作。感谢您拯救我的一天,非常感谢!
  • 谢谢你太多了,只要你接受答案就足够了。
猜你喜欢
  • 2022-01-13
  • 1970-01-01
  • 2013-11-27
  • 2018-11-26
  • 2018-10-29
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多