JQuery RestFul Put请求

时间:2013-07-22 08:40:21

标签: jquery rest servicestack

我试图调用ServiceStack中开发的restful服务。我已经成功地拨打了Get(s),但我很难打电话给Put或Post。 我的客户脚本。

function savePartner(e) {
            $.ajax({
                type: "PUT",
                contentType: "application/json; charset=utf-8",
                headers: {
                    'X-HTTP-Method-Override': 'PUT'
                },
                url: "http://localhost:49190/test",
                data: partnerInfoToJSON(),
                complete: function (data) { alert("complete"); },
                success: function (data) { alert("done"); },
                error:  function (data) { alert("failed");},
                dataType: "json"
            });
        }

        function partnerInfoToJSON() {
            return JSON.stringify({
                "Name": "TEST"
            });
        };

我确保服务器端的API工作的测试是在fiddler上完成的,但它确实有效。

我的服务代码:

[Route("/test/", "Put")]
public class TestDTO
{
    public string Name { get; set; }
}

public class TestDTOResponse
{
    public long ID { get; set; }
    public ServiceStack.ServiceInterface.ServiceModel.ResponseStatus ResponseStatus { get; set; }
}

[EnableCors(allowedMethods: "GET,POST,PUT,DELETE")]
public class TestService : ServiceStack.ServiceInterface.Service
{

    [EnableCors(allowedMethods: "GET,POST,PUT,DELETE")]
    public void Options(TestDTO testDTO)
    { 

    }

    public object Put(TestDTO testDTO)
    {
        try
        {
            return "Hallo World";
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

配置代码:

 Plugins.Add(new CorsFeature());

            RequestFilters.Add((httpReq, httpRes, requestDto) =>
                {
                    if (httpReq.HttpMethod == "OPTIONS")
                        httpRes.End();
                });
            base.SetConfig(new EndpointHostConfig
            {
                DebugMode = true,
                DefaultContentType = "application/json",
                GlobalResponseHeaders = {
                        { "Access-Control-Allow-Origin", "*" },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                        { "Access-Control-Allow-Headers", "Content-Type, origin, accept" },
                }
            });

1 个答案:

答案 0 :(得分:1)

从.ajax()方法的jQuery文档页面和“type”参数:

  

类型(默认:'GET')
  类型:字符串
  要求的类型(“POST”或“GET”),默认为“GET”。注意:此处也可以使用其他HTTP请求方法,例如PUT和DELETE,但并非所有浏览器都支持