【问题标题】:Pass a single parameter to WebApi controller using jQuery Ajax使用 jQuery Ajax 将单个参数传递给 WebApi 控制器
【发布时间】:2015-08-11 10:53:08
【问题描述】:

我正在尝试将单个参数(字符串值)传递给 webapi 控制器,但是它不起作用。参数值以“null”形式到达控制器。这是我的 WebApi 配置,

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}"
           );

        }
    }

控制器:

        [HttpPost]
        public HttpResponseMessage GetDataView(string request)
        { 
            try
            {
                var result = DB.GetDataView(request);

                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (Exception ex)
            {            
                //todo: log exception   
                throw ex;
            }
        }

AJAX

var serverName = 'ds100';
 $.ajax({
        url: 'api/ServerInfo/GetDataView',
        type: 'POST',
        dataType: 'json',
        data: serverName,
        success: function (data, textStatus, xhr) {

        },
        error: function (xhr, textStatus, errorThrown) {

        }

我错过了什么吗?任何帮助表示赞赏。

【问题讨论】:

  • 你可以在你的 ajax 方法中试试这个data: {request: serverName}
  • 你得到一个错误:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

标签: javascript jquery ajax asp.net-web-api


【解决方案1】:

问题似乎出在你身上

 var serverName = 'ds100';
 $.ajax({
    url: 'api/ServerInfo/GetDataView',
    type: 'POST',
    dataType: 'json',
    data: {request: serverName} ,
    success: function (data, textStatus, xhr) {

    },
    error: function (xhr, textStatus, errorThrown) {

    }

应该这样做

【讨论】:

  • 这对我有用,但使用类型:GET。我仍在找出为什么 type:POST 不起作用。代码完全一样,除了 POST
  • @SachinPakale 尝试过不设置dataType: 'json'?我认为这可能是问题所在,因为它是一个GET 请求,所有信息都应该放在 URL 中,我认为json 暗示它就像Body 中的那样,GET 请求不允许拥有。希望这会有所帮助
猜你喜欢
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2016-03-01
  • 2019-02-16
相关资源
最近更新 更多