asp.net web api: only during sql connection - HTTP 500 Error occurs : Local host is currently unable to handle request - asp.net

The Web Api throws HTTP 500 error when it has to reference values from sql database.
https://localhost:44304/api/values
This works fine.
But,
https://localhost:44304/api/User
throws HTTP 500 Error - Local host is currently unable to handle request
The API is a simple test one, which has to retrieve data from User table in SQL database.
private readonly string connectionString =
"Server=MyServerName\\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=True;user
id=dbuser;password=dbuserpass;";
The data access file:
namespace UserLogin.Models
{
public partial class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
No changes being done to any portions of the default code after creating the Web API Component.
Note: using udl, the test connection to the database was successful.
Thanks for help.

Related

Proactive messaging throwing Operation returned an invalid status code 'Unauthorized'

I'm trying to store the conversation reference for chats between user and our bot, and use that chat reference to send other messages later.
I'm saving the following entities in our DB:
string UserAadObjectId { get; set; }
string UserId { get; set; }
string UserName { get; set; }
string ConversationId { get; set; }
string ConversationType { get; set; }
string ConversationTenantId { get; set; }
string ChannelId { get; set; }
string ActivityId { get; set; }
string BotId { get; set; }
string BotName { get; set; }
string ConversationReference { get; set; }
string ServiceUrl { get; set; }
After getting these entities for a specific user, I'm creating a conversation reference as following:(Where chatReference is the sql database for the entities above)
var user = new ChannelAccount(chatReference.UserId, chatReference.UserName, null, chatReference.UserAadObjectId);
var bot = new ChannelAccount(chatReference.BotId, chatReference.BotName);
var conversationAccount = new ConversationAccount(conversationType: chatReference.ConversationType, id: chatReference.ConversationId, tenantId: chatReference.ConversationTenantId);
var convReference = new ConversationReference(activityId: chatReference.ActivityId, user: user, bot: bot, conversation: conversationAccount, channelId: chatReference.ChannelId, serviceUrl: chatReference.ServiceUrl);
When running:
await turnContext.SendActivityAsync(messageActivity);
I'm getting the following error from Bot Connector I think:
Operation returned an invalid status code 'Unauthorized'
{"message":"Authorization has been denied for this request."}
Why this is happening? Knowing that AppId and AppPwd are correct.
There are series of steps to be followed to avoid the error occurred.
1. Disable security and test on localhost
Check the App ID and password in configuration file and delete those for testing
"MicrosoftAppId": "",
"MicrosoftAppPassword": ""
As you are using the core .Net framework. add or edit settings in appsettings.json
2. Check the App ID and password of bot
Now need to check whether the App ID and password are matching or not.
These instructions and procedure include CURL usage
To verify that your bot's app ID and password are valid, issue the following request using cURL, replacing APP_ID and APP_PASSWORD with your bot's app ID and password.
curl -k -X POST https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token -d "grant_type=client_credentials&client_id=APP_ID&client_secret=APP_PASSWORD&scope=https%3A%2F%2Fapi.botframework.com%2F.default"
This request attempts to exchange your bot's app ID and password for an access token. If the request is successful, you will receive a JSON payload that contains an access_token property, amongst others.
{"token_type":"Bearer","expires_in":3599,"ext_expires_in":0,"access_token":"eyJ0eXAJKV1Q..."}
3. Enable security and test on localhost
<appSettings>
<add key="MicrosoftAppId" value="APP_ID" />
<add key="MicrosoftAppPassword" value="PASSWORD" />
</appSettings>
if you are using bot framework SDK for .NET use the above code block
For complete reference of the procedure. Check

I could not connect to database instance created with Entity Framework generated from model

I created a web application and a model. Then I generated a dbcontext class and a database instance. After I built the project, I tried to connect to that database from Server Explorer in Visual Studio, but could not connect.
I tried to test connection but got an error:
This connection cannot be tested because the specified database does not exist or is not visible to the specified user
Whenever I tried to scaffold view or controller I got this error:
Unable to retrieve metadata for ... one or more validation errors were detected during model generation
ModelsTable is based on type TestModel that has no keys defined.
When I created database object in controller class and write query got same error no key defined.
Also made updates on packages and tried again. I think my connection string is correct.
Here is my model.
public class TestModel
{
[Key]
public string ID { get; } = Guid.NewGuid().ToString();
public string AreaName { get; set; }
public bool IsWorking { get; set; }
public string UserName { get; set; }
public DateTimeOffset Time { get; set; }
}
So I could not use scaffolding, Entity Framework and write query.
Here is my dbcontext class.
public class ModelDB : DbContext
{
public ModelDB()
: base("name=ModelDB")
{
}
public DbSet<TestModel> ModelsTable { get; set; }
}
I searched on internet tried founded solutions but did not understand and could not solve. I hope did not ask unnecessary questions. Thanks for your helping.
Are you using Code First? If so I think you need to generate migrations.
In visual studio go to Package Manager Console and run this commands:
Add-Migration "modelClassName"
Update-Database –Verbose
For more information refer to this link: https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx
You are missing the set; in the field ID.

ASP.Net Web API Client Side Access

I am struck in an issue:
Below is my controller code:
and this is how I am trying to access this method on client side:
I am getting internal server error:
500 (Internal Server Error)
You could actually achieve the same in a more simpler way, see the working example -
public class Test
{
public string UserName { get; set; }
public string Password { get; set; }
}

Create DB context in different project

There is option to create DB which the DB context not allocated in the same MVC project,
i.e create one MVC in project A and the DB context in In project B which can use the model of model A
The reason is that I want to access to the DB from different project without any dependence
Edit.
I've created this in project A and generate the view and controller by scaffold and its working,now what should I do in project B to access to this DB context?
namespace DiffDBContext2.Models
{
public class Ad
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class AdModelDbContext : DbContext
{
public DbSet<ad> Ad { get; set; }
}
}
I am not sure what do you exactly want. But what I feel is that you want to have data access later as a separate project than your client (mvc). In this case you can have you dbcontext in another project but you need to have connection string in both mvc and data access project. when executing it always request connection string from client.

ASP.NET MVC API model not parsing

I am having some problems parsing my model in ASP.NET MVC API
This is my API controller:
public class UserController : ApiController
{
// Hent liste af personer
public IEnumerable<UserModel> Get()
{
return new UserModel[] { new UserModel(), new UserModel() };
}
// Hente enkelt person
public UserModel Get(int id)
{
return new UserModel();
}
// Opret person
[ValidationActionFilter]
public CreateUserRespose Post([FromBody]UserModel model)
{
CreateUserRespose rs = new CreateUserRespose();
return rs;
}
// Rediger person
public UserModel Put(int id, [FromBody]UserModel model)
{
return new UserModel();
}
// Slet person
public UserModel Delete(int id)
{
return new UserModel();
}
}
}
And the UserModel:
public class UserModel
{
[Required]
[StringLength(500)]
public String FristName { get; set; }
[Required]
[StringLength(500)]
public String LastName { get; set; }
[Required]
[StringLength(250)]
public String Email { get; set; }
[Required]
public String MatrikelId { get; set; }
}
When I call though Fiddler to the Post command with the following body
FirstName=Fistname MiddleName&LastName=SomeName&Email=email#email.us&MatrikelId=1234
Will the action Post be called, but the model is null, and ModelState.IsValid is true, the same happens if I send no data with the body!
What am I doing wrong here?
Update:
I have tryed sending the data as json instead
Fiddler:
User-Agent: Fiddler
Host: localhost:51268
Content-Length: 102
Content-type: application/json
{"FristName":"Kasper asdasd","LastName":"asdasdasd","Email":"asdaasd#asdasd.us","MatrikelId":"132456asd"}
But should the model state not be invalid when the model is null?
The ASP.NET Web API is using content negotiation process in order to decide which MediaTypeFormatter to use for deserializing the body of the request. For the typical POST request it will check for Accept and Content-Type headers. If none is present it will use the first MediaTypeFormatter on the list (by default it is JsonMediaTypeFormatter).
In your case Web API was unable to determine the proper MediaTypeFormatter. Adding a Content-Type header with value of application/x-www-form-urlencoded to the request should resolve the issue.
If you want to get more detailed knowledge regarding Formatters, Model Binding and Content Negotiation in ASP.NET Web API I would suggest following reading:
Designing Evolvable Web APIs with ASP.NET -> Chapter 8. Formatters and Model Binding (you should look very close at the entire book if you are interesed in learning ASP.NET Web API)
Everything you want to know about ASP.NET Web API content negotiation

Resources