Web API Client Posting Not Hitting Database - asp.net-mvc-4

Kindly help with ASP.NET MVC 4 Web Api project. I can retrieve JSON from my api controller without hitch, and posting seems to work (my UI is updated), but data is not hitting the database.
// POST api/todoes
public HttpResponseMessage Post(Todo item)
{
item = _db.Todoes.Add(item);
var response = Request.CreateResponse(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.TodoId });
response.Headers.Location = new Uri(uri);
return response;
}
self.create = function (formElement) {
// If valid, post the serialized form data to the web api
//$(formElement).validate();
//if ($(formElement).valid()) {
$.post(baseUri, $(formElement).serialize(), null, "json")
.done(function (o) { self.todoes.push(o); });
//}
}
'Am I doing something wrong?

Thanks all. I have the answer now ... _db.SaveChanges() commits to database.

Related

Vue app and .NET Core Web Api losing session

I hope this has not already been asked, I can't seem to find what I need. I have a VUE 3 app and am using a .NET Core Web API to retrieve data from a service. In the Vue app I make an axios call to log in the user
await axios({
method: 'post',
url: 'https://localhost:44345/api/Authentication/SignIn',
contentType: "application/json",
params: {
username: signInData.value.username,
password: signInData.value.password,
keepMeSignedIn: signInData.value.keepMeSignedIn
}
}).then(response => {
if (response.data.succeeded) {
console.log("Result: ", response.data.data);
}
else {
emit('handleServerSideValidationErrors', response);
}
This then calls my API where I call the service to sign in the user. Once I have verified the information and have the user data it is getting set in session.
public void Set<T>(string key, T value)
{
if (key.IsNullOrEmpty())
{
throw new Exception("The key parameter for SessionUtil.Set is required. It cannot be null/empty.");
}
else
{
this._validateSessionObjectVersion();
if (value == null)
{
Remove(key);
}
else
{
string json = JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
_httpContextAccessor.HttpContext.Session.SetString(key, json);
}
}
}
The issue I am running into is, when I go to another page that needs to access this session it is null. The API calls this get method but is null.
public T Get<T>(string key)
{
T value = default(T);
if (key.IsNullOrEmpty())
{
return value;
}
if (_httpContextAccessor.HttpContext == null)
{
return value;
}
this._validateSessionObjectVersion();
string json = _httpContextAccessor.HttpContext.Session.GetString(key);
if (!json.IsNullOrEmpty())
{
value = JsonConvert.DeserializeObject<T>(json);
}
return value;
}
My Vue app is running on localhost:5001 while my API is running on localhost:44345. I do have a cors policy already in place which allows me to call the API but I don't see what I need to do in order to not lose session.
Turns out my issue was I had set the cookie option of SameSite to SameSiteMode.Lax. As soon as I changed it to SameSiteMode.None it was working for me.

Stripe ASP.NET Core Webhook always returns BadRequest

I am currently working on a project and integrating Stripe payment. So far I have done the Stripe Checkout Session with the prebuilt template from here - https://stripe.com/docs/payments/accept-a-payment?integration=checkout. This is what I have done:
[HttpPost]
public async Task<ActionResult> CreateCheckoutSession()
{
var consultation = await this.offerService.GetOnlineConsultationModelAsync();
var options = new SessionCreateOptions
{
CustomerEmail = this.User.FindFirst(ClaimTypes.Email).Value,
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
UnitAmount = (long)(consultation.Price * 100),
Currency = "bgn",
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = consultation.Name,
Images = new List<string>
{
"https://res.cloudinary.com/dpo3vbxnl/image/upload/v1641585449/pediamed/onlineConsultation_vyvebl.jpg"
}
},
},
Quantity = 1,
},
},
PaymentIntentData = new SessionPaymentIntentDataOptions
{
CaptureMethod = "automatic",
},
PaymentMethodTypes = new List<string>
{
"card"
},
Mode = "payment",
SuccessUrl = "http://pediamed-001-site1.btempurl.com/Checkout/SuccessfulPayment",
CancelUrl = "http://pediamed-001-site1.btempurl.com/Checkout/CanceledPayment",
};
var service = new SessionService();
try
{
var session = service.Create(options);
await this.paymentService.CreateChekoutSession(session.Id, session.PaymentIntentId, session.ClientReferenceId);
Response.Headers.Add("Location", session.Url);
return new StatusCodeResult(303);
}
catch (StripeException ex)
{
System.Console.WriteLine(ex.StripeError.Message);
return BadRequest(new { Message = ex.StripeError.Message });
}
}
So far so good - everything works. Then I created the template from the Fulfill your orders article - https://stripe.com/docs/payments/checkout/fulfill-orders. This is what I currently have:
[HttpPost]
public async Task<IActionResult> Index()
{
string secret = "whsec_......";
var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
try
{
var stripeEvent = EventUtility.ConstructEvent(
json,
Request.Headers["Stripe-Signature"],
secret
);
// Handle the checkout.session.completed event
if (stripeEvent.Type == Events.CheckoutSessionCompleted)
{
var session = stripeEvent.Data.Object as Session;
// Fulfill the purchase...
await this.FulfillOrder(session);
}
return Ok();
}
catch (StripeException ex)
{
return BadRequest(new {message = ex.StripeError.Message});
}
}
The problem is when I use the Stripe CLI I get this:
Every time I get Bad Request, even in the details of the events in the Stripe Dashboard, but if I go to the payments dashboard they are all succeeded. Everything is done in localhost, but when deployed and using the correct api keys it is all the same. Can anyone help me with the Stripe webhook.
I suspect you might be using the signing secret from your dashboard, but when forwarding via the CLI using listen you need to use the CLI-specific signing secret that's provided in output when you run listen.
If that's not the case, can you provide more detail about the exception that's raised that leads to the bad request response path? ie, where in your code do you encounter an error?

How to post and redirect with Razor Pages

I do integration with payment gateway, which required post method. So I need to redirect from my page including post data to the payment gateway application under https
Following by this answer on this questions:
Post Redirect to URL with post data
How to make an HTTP POST web request
I not able found the right answer for my problem.
I'am using razor pages. Here is my code snippet
public async Task<IActionResult> OnGetAsync(int id)
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://example/payment/v1/easy", content);
var responseString = await response.Content.ReadAsStringAsync();
return Content(responseString);
}
I successfully get the response, but when I do return Content(responseString);. The page just show text only. Any idea how to solved this problem?

does the data sent to the server using http Post update the servers API url?

Im a newbie to flutter so please if you think the question context is wrong update it, im fetching a data from an SQl server to my flutter app, and i also want to send the users info back to the server after they fill out a form, im using the http.post and i get the response’s body correctly but when i open the Server Url (api url) i dont see it updated with the new info i posted to it, can someone please tell me how Post is supposed to work?
I'm new to Flutter too, this is a working example of how i understand it
class HttpService {
createUser(String name, String lastname) async {
Map data = {'name': name, 'lastname': lastname};
var body = json.encode(data);
var jsonResponse = null;
var response = await http.post(serverUrl + "/create/",
headers: {
HttpHeaders.authorizationHeader: '**Token_here_if_you_use_it**',
HttpHeaders.contentTypeHeader: "application/json",
}, body: body);
jsonResponse = json.decode(response.body);
if (response.statusCode == 201) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
print(jsonResponse.toString());
}
} else {
print(jsonResponse.toString());
}
}
}
In your main.dart :
final HttpService httpService = HttpService();
httpService.createUser(name,lastname);

posting object from angular 2 application to Web Api application (getting Unsupported Media Type)

I could use some guidens, sending an object from my angular 2 application to the Web API.
I know how to GET objects from the Web Api, to my angular 2 application, but can't seem to figure out how the post method works or even if I should use the http.post methodd.
My angular 2 application has the following method:
sendUpdatdReservation(updatedReservation: Reservation) {
var result;
var objectToSend = JSON.stringify(updatedReservation);
this.http.post('http://localhost:52262/api/postbookings', objectToSend)
.map((res: Response) => res.json()).subscribe(res => result = res);
console.log(result);
}
The "updatedReservation" is an object, which I convert to JSON.
The Web api can be reached by the following address:
httl://localhost:52262/api/postbookings
Web Api controller:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PostBookingsController : ApiController
{
[AcceptVerbs()]
public bool ConfirmBooking(Booking booking)
{
return true;
}
}
What I'm trying to do is to send the object, update my database based on the changes values that the object has. Then send back true or false if this is a confirmation or not so I can redirect to confirmation page.
Do any know the unsupported media type error?, is that related to that the object i send is not what the api method expects?
Hope someone can help.
You need to set the Content-Type header when sending the request:
sendUpdatdReservation(updatedReservation: Reservation) {
var result;
var objectToSend = JSON.stringify(updatedReservation);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:52262/api/postbookings', objectToSend, { headers: headers })
.map((res: Response) => res.json()).subscribe(res => {
this.result = res;
console.log(this.result);
});
}
Don't forget to import this class:
import {Http,Headers} from 'angular2/http';