使用自定义身份发布数据的Web API(Posting data to Web API using

2019-10-19 03:56发布

这是上一个后续较早前的问题使用HttpClient的使用Web API使用自定义的消息处理程序进行认证有关。

我可以使用所提供的解决方案从服务器请求数据,但现在我有麻烦张贴JSON数据到服务器。 每当我尝试发布数据到Web API,我现在回到内部服务器错误响应代码。

这是在客户端的代码:

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage();
    request.Headers.Add("X-Token", UserSession.GlobalInstance.SecurityToken);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    request.Method = HttpMethod.Post;
    request.RequestUri = new Uri(_apiBaseAddress + "api/User");
    request.Content = new ObjectContent<UserDTO>(userDTO, new JsonMediaTypeFormatter());

    var response = httpClient.SendAsync(request).Result;
    if (response.IsSuccessStatusCode)
    {
        // handle result code
    }

    throw new Exception(String.Format("Server generated error response: {0}", response.StatusCode));
}

用于控制器方法的声明:

public class UserController : ApiController
{
    public long Post(UserDTO userDTO)
    {
        // create user and return custom result
        // code (e.g. success, duplicate email, etc...)
    }
}

(我还添加[FromBody]该方法的参数,但具有相同的结果结束)。

我的消息处理和路由配置代码的快照,可以发现在这里 。

Answer 1:

您的代码按预期工作...

在服务器端。 创建控制台应用程序并运行的NuGet

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Program.cs

internal class Program
{
    private static IDisposable _server;

    private static void Main(string[] args)
    {
        _server = WebApp.Start<Startup>("http://localhost:12345");
        Console.ReadLine();
        _server.Dispose();
    }
}

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
    } 
}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var userTokenInspector = new UserTokenInspector {InnerHandler = new HttpControllerDispatcher(config)};
        config.Routes.MapHttpRoute(
            "UserAuthenticationApi",
            "api/{controller}/Authenticate",
            new {controller = "User", action = "Authenticate"},
            null
            );

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional},
            null,
            userTokenInspector
            );
    }
}

UserTokenInspector.cs

public class UserTokenInspector : DelegatingHandler {
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
    CancellationToken cancellationToken) {
        const string TOKEN_NAME = "X-Token";

        if (!request.Headers.Contains(TOKEN_NAME)) {
            return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.Unauthorized,
            "Request is missing authorization token."));
        }

        try {
            //var token = UserToken.Decrypt(request.Headers.GetValues(TOKEN_NAME).First());

            // validate token
            // ...
            // ...

            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("alex"), new string[] { });
        }
        catch {
            return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token."));
        }

        return base.SendAsync(request, cancellationToken);
    }
}

UserController.cs

public class UserController : ApiController
{
    public long Post(UserDTO userDTO)
    {
        // create user and return custom result
        // code (e.g. success, duplicate email, etc...)
        return 1;
    }
}

UserDto.cs

public class UserDTO
{
    public string Username { get; set; }
}

ValuesController.cs

public class ValuesController : ApiController
{
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "yay");
    }
}

客户端...创建一个控制台应用程序并运行的NuGet:

Install-Package Microsoft.AspNet.WebApi.Client

Program.cs

internal class Program
{
    private static void Main(string[] args)
    {
        var request = new HttpRequestMessage();
        request.Headers.Add("X-Token", "token");
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Method = HttpMethod.Post;
        var baseAddress = "http://localhost:12345/";
        request.RequestUri = new Uri(baseAddress + "api/User");
        var userDto = new UserDTO() {Username = "Alex"};
        request.Content = new ObjectContent<UserDTO>(userDto, new JsonMediaTypeFormatter());
        var httpClient = new HttpClient();
        var response = httpClient.SendAsync(request).Result;
        if (response.IsSuccessStatusCode)
        {
            // handle result code
            Console.WriteLine(response.StatusCode);
            Console.ReadLine();
        }
    }
}


文章来源: Posting data to Web API using custom Authentication