简体   繁体   English

POST Web API上的内部错误500

[英]Internal error 500 on POST web api

I have a problem with my web api application. 我的Web API应用程序有问题。 I get an internal error 500 when i try to post(save) a new user in my db. 当我尝试在数据库中发布(保存)新用户时,出现内部错误500。 The function bellow is the one that i use to make the client call. 下面的函数是我用来进行客户端调用的函数。

public void InsertNewUser(RegisterModel pNewUser, string pEmail)
{
    // Build rest uri
    string lREST_Uri_Browse = string.Format(@"api/accountapi/saveuserdata"
    // User data
    /*pModelSerialized*/);

    // Complete URI
    string lREST_Uri = Helpers_API.endPoint + lREST_Uri_Browse;

    var client = new HttpClient();

    client.BaseAddress = new Uri(Helpers_API.endPoint);

        var newUser = new Models.Models_API.Users
        {
            Email = pNewUser.Email,
            FName = pNewUser.FName,
            LName = pNewUser.LName,
            Inserted = DateTime.Now,
            ActiveAcc = true,
            AccType = pNewUser.AccType,
            BCompanyID = pNewUser.CompanyID,
            PID = pNewUser.PID,
            Password = pNewUser.Password,
            Token = GetToken(pEmail),
            ThirdParty = 0,
            Gender = pNewUser.Gender,
            BirthDate = pNewUser.BirthDate
        };

        // Add an Accept header for JSON format.
        //client.DefaultRequestHeaders.Accept.Add(
        //    new MediaTypeWithQualityHeaderValue("application/json"));
        // Create the JSON formatter.
        MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

        // Use the JSON formatter to create the content of the request body.
        HttpContent content = new ObjectContent<Models.Models_API.Users>(newUser, jsonFormatter);

        var result = client.PostAsync(lREST_Uri_Browse, content).Result;
}

This is the model 这是模特

public class Users
{
    public int BrokerID { get; set; }
    public DateTime Inserted { get; set; }
    public string Email { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool ActiveAcc { get; set; }
    public int BCompanyID { get; set; }
    public int PID { get; set; }
    public int AccType { get; set; }
    public string Password { get; set; }
    public string Token { get; set; }
    public int Gender { get; set; }
    public DateTime BirthDate { get; set; }
    public int ThirdParty { get; set; }
}

And bellow is the POST in APIController: 下面是APIController中的POST:

public HttpResponseMessage SaveUserData(Users pNewUser)
    {
        bool createUser = false;
        // First check for provided email in DB
        Users existingUser = asigCtx.Users.Where(u => u.Email == pNewUser.Email).SingleOrDefault();
        if (existingUser == null)
            createUser = true;
        else if (existingUser.ActiveAcc)
            createUser = true;

        if (createUser)
        {
            using (asigCtx = new AsigPrimeContext())
            {
                Users user = new Users()
                {
                    Email = pNewUser.Email,
                    FName = pNewUser.FName,
                    LName = pNewUser.LName,
                    Inserted = DateTime.Now,
                    ActiveAcc = true,
                    AccType = pNewUser.AccType,
                    BCompanyID = pNewUser.BCompanyID,
                    PID = pNewUser.PID,
                    Password = pNewUser.Password,
                    Token = pNewUser.Token,
                    ThirdParty = 0,
                    Gender = pNewUser.Gender,
                    BirthDate = pNewUser.BirthDate,
                };

                asigCtx.Users.Add(user);

                asigCtx.SaveChanges();
            }
        }
        var response = Request.CreateResponse<Users>(HttpStatusCode.Created, pNewUser);
        return response;
    }

Can anyone give me piece of advice with this code because i'm new in this and i just want to do it wright. 任何人都可以通过这段代码给我一些建议,因为我是新手,我只想这样做。 TNX TNX

You have an error in your code. 您的代码中有错误。 A 500 error indicates that your code contains an unhandled exception that killed its worker process. 错误500表示您的代码包含未处理的异常,该异常杀死了其工作进程。

Change your web.config file so that your application outputs the full error message. 更改您的web.config文件,以便您的应用程序输出完整的错误消息。

A few things I would check/try to get to the bottom of the issue: 我将检查/尝试深入了解问题的几件事:

  1. Is the code above exactly the same as in your application or have you changed anything (even if only to make it simpler)? 上面的代码是否与您的应用程序中的代码完全相同,或者您是否进行了任何更改(即使只是为了使其更简单)?

  2. Is the Users object used in SaveUserData controller method definitely from the same assembly as the one that you are posting from the InsertNewUser method? 在SaveUserData控制器方法中使用的Users对象是否一定与从InsertNewUser方法中发布的程序集来自同一程序集?

  3. Is the Users object complete on the listing (eg does it have any constructors)? 清单上的Users对象是否完整(例如,它有没有构造函数)?

  4. Have you tried executing the request to the endpoint through fiddler? 您是否尝试过通过提琴手向端点执行请求? This way you take any potential bugs in the client call out of the equation to see if the controller method on its own works. 这样,您可以消除客户端调用中的所有潜在错误,从而查看控制器方法是否有效。

  5. I've noticed this line: 我注意到这一行:

     string lREST_Uri_Browse = string.Format(@"api/accountapi/saveuserdata" // User data /*pModelSerialized*/); 

    Are you formatting the url and passing any params to it? 您要格式化url并将任何参数传递给它吗? If so, what are the params and what does your WebApi route look like? 如果是这样,那么参数是什么?您的WebApi路由是什么样的?

That should be enough for a start - let me know how you get on. 一开始就足够了-让我知道你的生活。


BTW: Two things that strike me in your code (unrelated to the question): 顺便说一句:在您的代码中有两点让我印象深刻(与问题无关):

  • It's very confusing to have a class called 'Users' representing a single user. 有一个名为“ Users”的类代表一个用户是非常令人困惑的。 If it's you're code I'd advise to change that to singular. 如果是您的代码,建议将其更改为单数。

  • the properties on the Users object are using abbreviations - I don't think it's that expensive to spell them out and I can guarantee you that anyone new to this code will be grateful if you put a full name rather than a mysterious BCompanyID , or less mysterious but still hard to read (and write for that matter) FName Users对象上的属性使用缩写词-我认为将它们拼写起来并不昂贵,而且我可以保证,如果您输入全名而不是一个神秘的BCompanyID或更少,那么对此代码不BCompanyID任何人都将不胜感激。神秘但仍然难以阅读(并为此写) FName

I had the same problem a few weeks ago. 几周前我遇到了同样的问题。 After doing a few tests, I've realized that my WebApi application was using DataContractJsonSerializer by default, instead of Newtonsoft. 经过一些测试之后,我意识到我的WebApi应用程序默认使用的是DataContractJsonSerializer,而不是Newtonsoft。 To fix it, you can change the default serializer on your server to NewtonSoft or to use DatacontractJsonSerializer to serialize your object and pass it to HttpWebRequest. 要解决此问题,您可以将服务器上的默认序列化程序更改为NewtonSoft,或使用DatacontractJsonSerializer序列化对象并将其传递给HttpWebRequest。

I would use jQuery to post some Json to the same URL ( $.post(@"api/accountapi/saveuserdata", { Email: "e@example.com", FName = "Vlad" ... }) ), thus eliminating InsertNewUser from the equation. 我将使用jQuery将一些Json发布到同一URL( $.post(@"api/accountapi/saveuserdata", { Email: "e@example.com", FName = "Vlad" ... }) ),因此从等式中消除InsertNewUser If you still get a null pNewUser parameter in SaveNewuser , then I would look at your API's route configuration to make sure the server expects SaveUserData(Users) . 如果您在SaveNewuser仍然得到一个空的pNewUser参数,那么我将查看您API的路由配置,以确保服务器期望SaveUserData(Users) If you get a non-null pNewUser from jQuery, then I would look closer at the output from InsertNewUser . 如果您从jQuery获得非null的pNewUser ,那么我将更仔细地看一下InsertNewUser的输出。 If I had to bet, I would put my money on the routing configuration. 如果必须下注,我会把钱花在路由配置上。

it seemed that i had an error with the LINQ code 似乎我的LINQ代码有错误

Users existingUser = asigCtx.Users.Where(u => u.Email == pNewUser.Email).SingleOrDefault();

After i solved this the request was ok. 我解决了这个问题后,请求就可以了。

Tnx for the help :) Appreciate. Tnx的帮助:)感激。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM